package com.orangelife.mobile.download;

import android.graphics.Bitmap;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;

import com.curry.android.util.StringUtil;
import com.curry.android.util.ToastHelper;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.orangelife.mobile.web.WebWhat;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 图片下载器
 * <p/>
 * Created by HeYuCan on 2016/8/23.
 *
 * @author hyc
 * @since v3.8.2
 */
public class ImageDownloader {
    private static final String savePath = "/sdcard/OrangeLife/loadedImages/";

    /**
     * //     * 下载或从内存、硬盘加载图片
     *
     * @param imageURL 图片的下载地址,当存在图片缓存时,相当于取出图片的key
     * @param iv       展示图片,若不需要可传入null
     */
    public static void loadImage(final String imageURL, ImageView iv, final boolean isShowLoadCompleted, final Handler handler) {
        if (StringUtil.isBlank(imageURL)) {
            ToastHelper.getInstance()._toast("传入的imageURL不能为:" + String.valueOf(imageURL));
            return;
        }
        if (iv == null) {
            ImageLoader.getInstance().loadImage(imageURL, new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String s, View view) {

                }

                @Override
                public void onLoadingFailed(String s, View view, FailReason failReason) {

                }

                @Override
                public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                    if (!android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState())) {
                        ToastHelper.getInstance()._toast("请检查是否存在sd卡");
                        return;
                    }
                    File file = new File(savePath);
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    String pngPath = new StringBuilder()
                            .append(savePath)
                            .append(System.currentTimeMillis())
                            .append(".png")
                            .toString();

                    File file1 = new File(pngPath);
                    try {
                        FileOutputStream out = new FileOutputStream(file1);
                        if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                            out.flush();
                            out.close();
                            if (isShowLoadCompleted) {
                                if (handler != null) {
                                    handler.obtainMessage(WebWhat.IMAGE_LOAD_COMPLETED, pngPath).sendToTarget();
                                }
                            }
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                        ToastHelper.getInstance()._toast("保存图片失败");
                    }

                }

                @Override
                public void onLoadingCancelled(String s, View view) {

                }
            });
        } else {
            ImageLoader.getInstance().displayImage(imageURL, iv);
        }
    }

    /**
     * 获取下载的图片所在的硬盘位置(前提是ImageLoader.getInstance()这个对象在application配置过缓存到disk)
     *
     * @param url 下载图片的url,作为取出该图片的key
     */
    public static String getImgPath(String url) {
        File file = ImageLoader.getInstance().getDiskCache().get(url);
        if (file == null) {
            return "";
        }
        return file.getPath();
    }

}
